#!/bin/bash
function install_nginx() {
    echo -e "${blue}当前正在执行的操作为:${nocolor} ${green}安装Nginx${nocolor}"
    echo ""
    nginxPid=`pidof nginx`
    if [ -n "$nginxPid" ];then
        echo -e "$Warn 系统已存在Nginx，请删除后继续！！！"
        anykeyback
        return 1
    fi
    rm -rf /etc/rc.d/init.d/nginx >>/dev/null 2>&1
    rm -rf /etc/systemd/system/nginx.service >>/dev/null 2>&1
    systemctl daemon-reload >>/dev/null 2>&1
    systemctl disable nginx >>/dev/null 2>&1
    
    while [[ ! ${nginxVer_digit} =~ ^[0-9]+$ || "$nginx_dot" == "0" || "$nginx_endwith" == "." ]]
    do
        echo -ne "输入需要安装的Nginx版本[1.18.0], 列出版本Hh[行数]: "
        read nginxVer
        nginxVer=${nginxVer:-1.18.0}
        nginxVer=`echo $nginxVer`
        nginxVer_digit=${nginxVer//./}
        nginx_dot=$(echo $nginxVer|grep -o "\."|wc -l)
        nginx_endwith=${nginxVer:0-1}
        nginxVer_=${nginxVer^^}
        if [[ ${nginxVer_} =~ H[0-9]*$ ]];then
            if [ "$die_network" == "ture" ];then
                    echo -e "$Info 设备未联网，不支持查询"
            else
                show_lines=$(echo $nginxVer|egrep -o "[0-9]*"|head -n1)
                if [ "X$show_lines" == "X" ];then
                    show_lines=25
                fi
                curl -so $workHome/logs/nginx.xml https://repo.huaweicloud.com/nginx/
                cat $workHome/logs/nginx.xml|egrep -o "nginx-[0-9.]+\.tar\.gz"|sort -ruV|awk -F"-" '{print $2}'|sed 's/.tar.gz//g'|head -n $show_lines
            fi
        else
            if [[ ! ${nginxVer_digit} =~ ^[0-9]+$ || "$nginx_dot" == "0" || "$nginx_endwith" == "." ]];then
                echo -e "$Warn nginx版本号只能由数字和.组成，且不以.结尾，请重新输入！"
                sleep 0.5
            fi    
        fi
    done
    echo ""
    
    if [ ! -f $workHome/packages/nginx/nginx-$nginxVer.tar.gz -a "$die_network" == "ture" ];then
        echo -e "$Error 系统未联网，且本地不存在需要安装的Nginx版本！！！"
        anykeyback
        return 1
    fi
    
    echo -ne "设置Nginx安装位置[/usr/local/nginx]: "
    read -e nginxPath
    nginxPath=${nginxPath:-/usr/local/nginx}
    nginxPath=`echo $nginxPath`
    nginxPath=${nginxPath%/}
    echo ""
    isNull=`ls $nginxPath/* 2>/dev/null | wc -l`
    if [[ $isNull -gt 0 ]];then
        echo -ne  "Nginx安装目录非空，继续安装会删除已有数据！\n继续[Yy,Enter],退出[Nn]: "
        read isYn
        if [[ $isYn == [Nn] ]];then
         sleep 0.10
         return 1        
        fi
        echo ""
    fi
    
    command -v ss >/dev/null 2>&1
    if [ "$?" == "0" ];then
        listen_cmd="ss -lnpt"
    else
        command -v netstat >/dev/null 2>&1
        if [ "$?" == "0" ];then
          listen_cmd="netstat -tnlp"
        fi
    fi
    [[ $listen_cmd ]] && PortCheck=Yes || PortCheck=No
    PortUsed=
    PortUsed_Pro=
    nginxPort=
    while [[ ! "$nginxPort" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        echo -ne "请输入Nginx监听端口[80]: "
        read nginxPort
        nginxPort=${nginxPort:-80}
        if [[ ! "$nginxPort" =~ ^[1-9][0-9]+$ ]];then
             echo -e "$Warn Nginx端口为不为零的两位以上数字，请重新输入！"
             sleep 0.5
        else
            if [ "$PortCheck" == "Yes" ];then
                PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${nginxPort} "`
                if [ -n "$PortUsed_Pro" ];then
                  PortUsed=Yes
                  echo -e "$Warn Nginx端口已被使用，请重新输入！"
                else
                  PortUsed=No
                fi
            else
                PortUsed=No
            fi
        fi
    done
    echo ""
    
    echo -ne "$blue Nginx安装信息汇总 $nocolor
---------------------------------
Nginx版本：$nginxVer
Nginx安装位置：$nginxPath
Nginx端口：$nginxPort
---------------------------------
继续[Yy,Enter],退出[Nn]: "
    read isYn
    if [[ $isYn == [Nn] ]];then
        sleep 0.10
        return 1
    fi
    echo ""
    
    nginxHome="$workHome/packages/nginx"
    cd $nginxHome
    
    echo -e "${cyan}将开始nginx安装过程${nocolor}"
    echo ""
    if [ "$die_network" == "true" ];then
        ping -c 2 -w 5 180.76.76.76 >/dev/null 2>&1
        if [ "$?" != "0" ];then
           die_network="true"
        else
           die_network="false"
        fi
    fi
    if [[ ! -f ${nginxHome}/nginx-${nginxVer}.tar.gz && "$die_network" == "false" ]];then
        echo -e "$Info ${purple}下载nginx安装包${nocolor}"
        
        echo -e "$Info ${purple}从华为云下载nginx${nocolor}"
        curl --progress-bar --connect-timeout 30 -m 600 -O --fail https://repo.huaweicloud.com/nginx/nginx-${nginxVer}.tar.gz
        if [ "$?" != "0" ];then
            echo -e "$Info ${purple}从官网下载nginx${nocolor}"
            curl --progress-bar --connect-timeout 30 -m 600 --fail -O http://nginx.org/download/nginx-${nginxVer}.tar.gz
        fi
                
        if [ "$?" != "0" ];then
           echo -e "$Error 下载nginx失败，请检查网络或者不存在此版本的Nginx!"
           anykeyback
           return 1
        fi
    elif [[ ! -f ${nginxHome}/nginx-${nginxVer}.tar.gz && "$die_network" == "true" ]];then
        echo -e "$Error 你的主机未联网，请提前手动下载安装包，使用离线安装！！！"
        anykeyback
        return 1
    fi

    echo -e "$Info ${purple}安装所需基础RPM包${nocolor}"
    yum -y install make gcc-c++ cmake bison-devel ncurses-devel gcc perl wget unzip bison bzip2 \
    glibc glibc-devel openssl-devel openssl libaio-devel autoconf automake  libxml*  libtool-ltdl-devel*
    if [ "$?" != "0" ];then
        echo -e "$Error 基础依赖软件失败，退出安装!"
        anykeyback
        return 1
    fi
    
    for i in make gcc gcc-c++ cmake openssl openssl-devel glibc glibc-devel automake perl autoconf
    do
        rpm -q $i >/dev/null 2>&1
        if [ "$?" != "0" ];then
            echo -e "$Error 基础依赖软件${i}安装失败，退出安装!"
            anykeyback
            return 1
        fi
    done
    
    find $nginxHome/* -type d|xargs rm -rf
    
    echo -e "${blue}安装zlib$nocolor"
    cd $nginxHome
    zlibPack=`ls -r |grep zlib|head -n 1`
    if [ -z "$zlibPack" ];then
        echo -e "$Info ${purple}下载zlib${nocolor}"
        curl --progress-bar --connect-timeout 30 -m 360 --fail -O http://www.zlib.net/zlib-1.2.11.tar.gz
        tar zxf zlib-1.2.11.tar.gz
        download_status=$?
        rm -rf zlib-1.2.11
    fi
    if [ "${download_status}" != "0" ];then
        rm -rf zlib-1.2.11.tar.gz
        curl --progress-bar --connect-timeout 30 -m 360 --fail -LkO https://gitee.com/ElvisTan/software-house/attach_files/974549/download/zlib-1.2.11.tar.gz
        tar zxf zlib-1.2.11.tar.gz >/dev/null 2>&1
        download_status=$?
        rm -rf zlib-1.2.11
    fi
    
    if [ "${download_status}" != "0" ];then
        rm -rf zlib-1.2.11.tar.gz
        echo -e "$Error zlib下载失败，退出安装！！！"
        anykeyback
        return 1
    fi
    
    zlibPack=`ls -r |grep zlib|head -n 1`
    zlibuPack=${zlibPack%.tar*}
    echo -e "$Info ${purple}解压zlib${nocolor}"
    echo $zlibPack|grep ".tar.gz" >/dev/null && tar zxf $zlibPack ||tar jxf $zlibPack && \
    cd $zlibuPack && \
    echo -e "$Info ${purple}预编译zlib${nocolor}" && \
    ./configure --prefix=/usr/local/zlib && \
    echo -e "$Info ${purple}编译zlib${nocolor}" && \
    make -j8 && \
    echo -e "$Info ${purple}安装zlib${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装zlib失败，退出安装！！！"
        anykeyback
        return 1
    fi

    echo -e "${blue}安装openssl$nocolor"
    cd $nginxHome
    opensslPack=`ls -r |grep openssl|head -n 1`
    if [ -z "$opensslPack" ];then
        echo -e "$Info ${purple}下载openssl${nocolor}"
        curl --progress-bar --connect-timeout 30 -m 360 --fail -LkO  https://gitee.com/ElvisTan/software-house/attach_files/974553/download/openssl-1.1.1k.tar.gz
        tar zxf openssl-1.1.1k.tar.gz >/dev/null 2>&1
        download_status=$?
        rm -rf openssl-1.1.1k
    fi
    if [ "${download_status}" != "0" ];then
        rm -rf openssl-1.1.1k.tar.gz
        curl --progress-bar --connect-timeout 30 -m 360 --fail -O https://www.openssl.org/source/openssl-1.1.1k.tar.gz
        tar zxf openssl-1.1.1k.tar.gz >/dev/null 2>&1
        download_status=$?
        rm -rf openssl-1.1.1k
    fi
    
    if [ "${download_status}" != "0" ];then
        rm -rf openssl-1.1.1k.tar.gz
        echo -e "$Error openssl下载失败，退出安装！！！"
        anykeyback
        return 1
    fi
    
    opensslPack=`ls -r |grep openssl|head -n 1`
    openssluPack=${opensslPack%.tar*}
    echo -e "$Info ${purple}解压openssl${nocolor}"
    echo $opensslPack|grep ".tar.gz">/dev/null && tar zxf $opensslPack ||tar jxf $opensslPack && \
    cd $openssluPack && \
    echo -e "$Info ${purple}预编译openssl${nocolor}" && \
    ./config --prefix=/usr/local/openssl && \
    echo -e "$Info ${purple}编译openssl${nocolor}" && \
    make -j8 && \
    echo -e "$Info ${purple}安装openssl${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装openssl失败，退出安装！！！"
        anykeyback
        return 1
    fi
 
    echo -e "${blue}安装pcre${nocolor}"
    cd $nginxHome
    pcrePack=`ls -r |grep pcre|head -n 1`
    apPcrePack=`ls -r $workHome/packages/apache/ 2>/dev/null|grep pcre|head -n 1`
    if [ -z "$pcrePack" ];then
        if [ -z "$apPcrePack" ];then
           echo -e "$Info ${purple}下载PCRE${nocolor}"
           curl --progress-bar --connect-timeout 30 -m 360 --fail -O https://ftp.pcre.org/pub/pcre/pcre-8.44.tar.bz2
           tar jxf pcre-8.44.tar.bz2 >/dev/null 2>&1
           download_status=$?
           rm -rf pcre-8.44
        else
           echo -e "$Info ${purple}从Apache安装目录复制Pcre${nocolor}"
           /bin/cp -f $workHome/packages/apache/$ngPcrePack .
           download_status=$?
        fi
    fi
    if [ "${download_status}" != "0" ];then
        rm -rf pcre-8.44.tar.bz2
        curl --progress-bar --connect-timeout 30 -m 360 --fail -LkO https://gitee.com/ElvisTan/software-house/attach_files/974552/download/pcre-8.44.tar.bz2
        tar jxf pcre-8.44.tar.bz2 >/dev/null 2>&1
        download_status=$?
        rm -rf pcre-8.44
    fi
    
    if [ "${download_status}" != "0" ];then
        rm -rf pcre-8.44.tar.bz2
        echo -e "$Error pcre下载失败，退出安装！！！"
        anykeyback
        return 1
    fi
    
    pcrePack=`ls -r |grep pcre|head -n 1`
    pcreuPack=${pcrePack%.tar*}
    echo -e "$Info ${purple}解压pcre${nocolor}"
    echo $pcrePack|grep ".tar.gz">/dev/null && tar zxf $pcrePack ||tar jxf $pcrePack && \
    cd $pcreuPack && \
    echo -e "$Info ${purple}预编译pcre${nocolor}"&& \
    ./configure --prefix=/usr/local/pcre && \
    echo -e "$Info ${purple}编译pcre${nocolor}" && \
    make -j8 && \
    echo -e "$Info ${purple}安装pcre${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装pcre失败，退出安装！！！"
        anykeyback
        return 1
    fi
    
    echo -e "${blue}安装nginx$nocolor"
    rm -rf $nginxPath
    cd $nginxHome
    echo -e "$Info ${purple}解压nginx${nocolor}"
    tar zxf nginx-${nginxVer}.tar.gz && cd nginx-${nginxVer} && \
    echo -e "$Info ${purple}预编译Nginx${nocolor}" && \
    ./configure --prefix=$nginxPath --with-http_stub_status_module --with-http_ssl_module --with-http_gunzip_module --with-http_gzip_static_module --with-pcre=$nginxHome/$pcreuPack --with-zlib=$nginxHome/$zlibuPack && \
    echo -e "$Info ${purple}编译Nginx${nocolor}" && \
    make -j8 && \
    echo -e "$Info ${purple}安装Nginx${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装nginx失败，退出安装！！！"
        anykeyback
        return 1
    fi
    
    echo -e "$Info ${purple}配置nginx服务脚本${nocolor}"
    if [[ $system_ver == [456] ]];then
        cat > /etc/rc.d/init.d/nginx <<'EOF'
#!/bin/bash
# nginx Startup script for the Nginx HTTP Server
# it is v.0.0.2 version.
# chkconfig: - 85 15
# description: Nginx is a high-performance web and proxy server.
# It has a lot of features, but it's not for everyone.
# processname: nginx
# pidfile: /var/run/nginx.pid
# config: $nginxPath/conf/nginx.conf
nginxd=$nginxPath/sbin/nginx
nginx_config=$nginxPath/conf/nginx.conf
nginx_pid=$nginxPath/logs/nginx.pid
RETVAL=0
prog="nginx"
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0
[ -x $nginxd ] || exit 0
# Start nginx daemons functions.
start() {
if [ -e $nginx_pid ];then
netstat -anpt |grep nginx >/dev/null
   if [ "$?" == "0" ];then
   echo "nginx already running...."
   exit 1
   fi
fi
echo -n $"Starting $prog: "
daemon $nginxd -c ${nginx_config}
RETVAL=$?
echo
[ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
return $RETVAL
}
# Stop nginx daemons functions.
stop() {
echo -n $"Stopping $prog: "
killproc $nginxd
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx $nginxPath/logs/nginx.pid
}
reload() {
echo -n $"Reloading $prog: "
#kill -HUP `cat ${nginx_pid}`
killproc $nginxd -HUP
RETVAL=$?
echo
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
stop
start
;;

status)
status $prog
RETVAL=$?
;;
*)
echo $"Usage: $prog {start|stop|restart|reload|status|help}"
exit 1
esac
exit $RETVAL
EOF
        sed -i "s#\$nginxPath#$nginxPath#g" /etc/rc.d/init.d/nginx
        chmod +x /etc/rc.d/init.d/nginx
        chkconfig --add nginx
    else
        cat >/etc/systemd/system/nginx.service<<'EOF'
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
Type=forking
PIDFile=$nginxPath/logs/nginx.pid
ExecStartPre=/usr/bin/rm -f $nginxPath/logs/nginx.pid
ExecStartPre=$nginxPath/sbin/nginx -t
ExecStart=$nginxPath/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target

EOF
        sed -i "s#\$nginxPath#$nginxPath#g" /etc/systemd/system/nginx.service
        systemctl daemon-reload
    fi
    
    echo -e "$Info ${purple}修改Nginx配置${nocolor}"
    sed -i '/pass the PHP scripts/{:a;n;s/#//g;/\}/!ba}' $nginxPath/conf/nginx.conf
    sed -i 's/\(fastcgi_param  SCRIPT_FILENAME\).*/\1 \$document_root\$fastcgi_script_name;/' $nginxPath/conf/nginx.conf
    sed -i "s/^[[:blank:]]*listen.*80;/        listen $nginxPort;/g" $nginxPath/conf/nginx.conf
    #添加phpinfo.php
    echo "<?php" >>$nginxPath/html/phpinfo.php
    echo "phpinfo();" >>$nginxPath/html/phpinfo.php
    echo "?>" >>$nginxPath/html/phpinfo.php
    #echo  "请使用浏览器访问\033[0m http://$ipaddr/phpinfo.php" >>$logs_file
    
    echo -e "$Info ${purple}启动Nginx，并设置开机启动${nocolor}"
    killall -9 nginx>/dev/null 2>&1
    if [[ $system_ver == [456] ]];then
        service nginx start
        chkconfig --level 2345 nginx on
    else   
        systemctl start nginx
        systemctl enable nginx >/dev/null 2>&1
    fi

    echo -e "$Info ${purple}检查nginx服务是否运行正常${nocolor}"
    nginxPid=`pidof nginx`
    if [ -z "$nginxPid" ];then
        $nginxPath/sbin/nginx >/dev/null 2>&1
        sleep 1
        nginxPid=`pidof nginx`
        if [ -z "$nginxPid" ];then
          echo -e "$Error nginx启动失败，可能为安装有问题或者端口被占用！！！"
        else
          echo -e "$Warn nginx服务脚本存在问题，无法控制nginx服务启停，请检查服务脚本！！！"
        fi
    else
        nginxVer=`$nginxPath/sbin/nginx -v 2>&1|awk -F"/" '{print $2}'`
        [[ "$nginxPort" = "80" ]] && requestURL="http://$ipaddr" || requestURL="http://$ipaddr:$nginxPort"
        echo -e "$Info ${light_geen}nginx $nginxVer安装完成${nocolor}
------------------------------------------------------
你可以通过使用service或systemctl命令来控制nginx启停
Nginx安装位置：$nginxPath
请访问 ${blue}$requestURL${nocolor} 检验nginx是否运行正常
------------------------------------------------------"
    fi
    anykeyback
}
